package com.example.demo;

import com.example.demo.annotions.WebPath;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Method;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * Created by Arat.Wu on 2018/10/09.
 */
@Component
public class WebPathScanner2 implements ApplicationListener<ContextRefreshedEvent> {

    private volatile AtomicBoolean isInit=new AtomicBoolean(false);
    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        //防止重复触发 主要因为对于web应用会出现父子容器，这样就会触发两次
        if(!isInit.compareAndSet(false,true)) {
            return;
        }
        ApplicationContext applicationContext = contextRefreshedEvent.getApplicationContext();
        Map<String, Object> beansWithAnnotation = applicationContext.getBeansWithAnnotation(Service.class);
        beansWithAnnotation.forEach((string,item)->{
            Method[] allDeclaredMethods = ReflectionUtils.getAllDeclaredMethods(item.getClass());
            for(Method mthod:allDeclaredMethods){
                if(null!=mthod.getAnnotation(WebPath.class)){
                    System.out.println(mthod.getName());
                }
            }
        });
    }
}
